<?php
namespace app\api\controller;

use think\Controller;
use think\Request;
use think\Session;
use think\Loader;
use think\Cache;
use think\Config;
use think\Log;
use think\Db;
use EasyWeChat\Factory;
use EasyWeChat\Payment\Application;
use EasyWeChat\Payment\Order;
use app\common\Tool\ApiErrDesc;

use app\model\UserModel;
use app\model\CodeModel;
use app\model\CompanyModel;
use app\common\BaseController;
use app\common\Auth\JwtAuth;


class Wechat extends BaseController
{
    private $table1 = 'commodity_orders';
    private $table_view_member= 'view_commodity_orders';
    private $token = '0b60f61f01ba6cb292b8ce3b5e822fbc';
    protected $wechatOA;
    // protected $request;

    public function _initialize(){
        // $this->request = Request::instance();
        $this->noNeedLogin = ['login','notify','share'];
        Loader::import('Wechat_OA', EXTEND_PATH);
        $this->wechatOA = new \Wechat_OA();

        if (isset($_GET['echostr'])) {
            $this->valid();
        }else{
            // $this->response_event();
        }
    }

    // public function __construct(){
    //     // $this->request = Request::instance();
        
    //     Loader::import('Wechat_OA', EXTEND_PATH);
    //     $this->wechatOA = new \Wechat_OA();

    //     if (isset($_GET['echostr'])) {
    //         $this->valid();
    //     }else{
    //         $this->response_event();
    //     }
    // }
    public function testwechat(){
        $res  = $this->wechatOA->easywechattest();
        var_dump($res);
        
    }
    /**微信支付-套餐
     * [wx_pay description]
     * @HtttpRequest                          get|post
     * @Author       GNLEON
     * @Param
     * body   ---- 充值内容
       out_trade_no   ----订单号
       total_fee   ------价格
       notify_url  ------回调
       openid   ---------用户openid
     * @DateTime     2020-08-14T10:13:56+0800
     * @LastTime     2020-08-14T10:13:56+0800
     * @return       [type]                   [description]
     */
    public function wx_pay(){
        /*
            套餐变更  code......

            套餐叠加  coed......
        */
        $commodityid = $this->request->param('commodityid');
        $commodityid_info = $this->find('commodity','id = '.$commodityid);
        if(!$commodityid_info){return toJson(['code'=>400,'message'=>'套餐不存在或已售空']);}
        if($commodityid_info['year']!=0){
                $commodity_type = 'Y';
            }elseif ($commodityid_info['month']!=0) {
                 $commodity_type = 'M';
                # code...
            }elseif ($commodityid_info['day']!=0) {
                 $commodity_type = 'D';
                # code...
            }else{
                return toJson(['code'=>400,'message'=>'商品信息不存在或已删除']);
            }


        $out_trade_no = $this->makeOrdersn(ApiErrDesc::Out_Trade_No[1][2].$commodity_type);
// $this->request->param('price')
        $data = [
            'body' => '套餐充值',
            'out_trade_no' => $out_trade_no,
            'total_fee' => $this->request->param('price'),
            'notify_url' => 'https://devs.zsicp.com/public/api/Wechat/notify',
            'openid' => $this->user['openid'],
            'uid'   => $this->uid
        ];

        $indata = [
            'userid' => $this->uid,
            'commodityId' => $this->request->param('commodityid'),
            'openid' => $this->user['openid'],
            'payType' => 1,
            'status' => 1,
            'amount' => $this->request->param('amount'),
            'price' => $this->request->param('price'),
            'createtime' => time(),
            'remark' => 'h5订单'
        ];
        $indata['tradeNo'] = $out_trade_no;
        //check change commodity
        $checkchange = '';
        $search[0] = 'userid = '.$this->uid;
        $search[1] = 'status = 2 and payTime is not null and deletetime is null';
        $search[3] = 'commodity_year = 0 and commodity_month = 1 and commodity_day = 0';
        $search[4] = 'expritime > '.time();
        $where = '';

        foreach ($search as $key => $value) {
            # code...
            if($value){
                $where=$where.$value.' and ';
            }
        }
        $where=substr($where,0,strlen($where)-5);
        $order = 'payTime desc';
        $memberinfo = Db::table($this->table_view_member)->where($where)->order($order)->find();

        if($memberinfo){
            if($memberinfo['commodityId']!=$this->request->param('commodityid')){
                $indata['createtime'] = time()+(30*24*3600);
                // $where = 'id = '.$memberinfo['commodityId'];
                // $changedata = [
                //     'deletetime' => time()
                // ];
                // $this->update($this->table1, $where, $changedata);
            }
        }

        /*end */

        try{
            $this->insert($this->table1,$indata);
        }catch (\Throwable $th) {
            exception(ApiErrDesc::ERR_PARAMS[1],ApiErrDesc::ERR_PARAMS[0]);
            }
        $res = $this->wechatOA->WeixinPrePay($data);

        return toJson($res);
    }

    /**
     * Notes:h5支付回调，根据订单号前两位判断交易类型，然后交给相应Model处理
     * @author:xxf
     * Date: 2020年10月10日 23:31:04
     * Time: 14:46
     * @param $type 支付类型
     * @throws \EasyWeChat\Kernel\Exceptions\Exception
     * @remark  支付回调,
     *          过期时间根据业务逻辑 调整 现以月为单位
     */
    public function notify(){
        $app = Factory::payment(Config::get('wx_config'));
        $response = $app->handlePaidNotify(
            function ($message, $fail) {
                Log::info('微信支付回调：' . json_encode($message));
                 //Log::info('微信支付回调测试：' . json_encode($message));
 
                if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                    // 用户是否支付成功
                    if ($message['result_code'] === 'SUCCESS') {

                        $where =  'tradeNo = "'.$message['out_trade_no'].'"';
                        $data = [
                            'status' => 2,
                            'expritime' => time()+(30*24*3600),
                            'payTime' => time() 
                        ];
                        //确认套餐类型
                        //
                        $commodity_date_type  = substr($message['out_trade_no'],2,1);
                        $action_date = 0;
                        switch ($commodity_date_type) {
                            case 'Y':
                                $data['expritime'] = time()+(365*24*3600);
                                $action_date = 365*24*3600;
                                # code...
                                break;
                            case 'M':
                                $data['expritime'] = time()+(30*24*3600);
                                $action_date = 30*24*3600;
                                # code...
                                break;
                            case 'D':
                                $data['expritime'] = time()+(1*24*3600);
                                $action_date = 1*24*3600;
                                # code...
                                break;
                            default:
                                # code...
                                break;
                        }
                        // $check_CH = $this->find($this->table1,$where);// 是否变更套餐
                        // if($check_CH){
                        //     $check_time = date("Y-m-d",$check_CH['createtime']);
                        //     $now_time = date("Y-m-d");
                        //     if($check_time == $now_time){
                        //         $data['expritime'] = time()+(60*24*3600);
                        //     }
                        // }
                        $this->update($this->table1, $where, $data);
                        $orderinfo = $this->find($this->table1,$where);
                        $commodityinfo = $this->find('commodity','id = '.$orderinfo['commodityId']);
                        $uinfo = $this->find('view_user','openid = "'.$orderinfo['openid'].'"');
                        
                        //会员信息(表)
                        $is_member = $this->find('store_member','openid = "'.$orderinfo['openid'].'"');
                        switch ($uinfo['roleid']) {
                            case '2':
                                $vip_level = 0;
                                // $vip_level = 1;
                                break;
                            case '8':
                                $vip_level = 0;
                                # code...
                                // $vip_level = 2;
                                break;
                            default:
                                $vip_level = 0;
                                # code...
                                break;
                        }
                        if($is_member){
                            $updata = [
                                // 'vip_date' => date("Y-m-d H:i:s",$data['expritime']),
                                'commodityid' => $orderinfo['commodityId'],
                                'headimg' => $uinfo['headimgurl'],
                                'phone' => $uinfo['mobile'],
                                'vip_level' => $vip_level,

                            ];
                            /**套餐叠加**/
                            if($is_member['commodityid'] == $orderinfo['commodityId']){
    
                                $updata['vip_date'] = date("Y-m-d H:i:s",strtotime($is_member['vip_date']) + $action_date);
                                
                            }
                            //积分
                            if($commodityinfo['type']==2){
                                $res = $this->member_integral($is_member['openid'],$commodityinfo['frequency'],'add','C');
                            }else{
                                $res = $this->member_integral($is_member['openid'],$commodityinfo['frequency'],'add','M');
                            }
                            Log::info("积分充值".$is_member['openid']."-".$res."-".$commodityinfo['type']);
                            //end
                            $this->update('store_member','openid ="'.$is_member['openid'].'"',$updata);

                        }else{
                            $inmember_data = [
                                'openid' => $uinfo['openid'],
                                'headimg' => $uinfo['headimgurl'],
                                'nickname' => $uinfo['nickname'],
                                'phone' => $uinfo['mobile'],
                                'username' => $uinfo['name'],
                                'vip_level' => 2,
                                'vip_date' => date("Y-m-d H:i:s",$data['expritime']),
                                'create_at' => date("Y-m-d H:i:s",time()),
                                'commodityid' => $orderinfo['commodityId'],
                                'frequency' => $commodityinfo['frequency'],


                            ];
                            $this->insert('store_member',$inmember_data);
                        }

                        //end
                        //
                        // $type = substr($message['out_trade_no'], 0, 2); //订单号前两位判断支付场景，CX促销活动，CZ普通充值
                        // switch ($type) {
                        //     case 'CZ';
                        //         $this->orderModel->payRechargeNotify($message);
                        //         break;
                        //     case 'CX';
                        //         $this->orderModel->payActivityNotify($message);
                        //         break;
                        //     default:
                        //         return $fail('单号异常，请稍后再通知我');
                        //         break;
                        // }
 
                        // 用户支付失败
                    } elseif($message['result_code'] === 'FAIL') {
                         $where =  'tradeNo = '.$message['out_trade_no'];
                         $data = [
                            'status' => 3, 
                        ];
                         $this->update($this->table1, $where, $data);
                        //db('user_orders')->where('id',$message['out_trade_no'])->update('status',7);
                    }
                } else {
                    return $fail('通信失败，请稍后再通知我');
                }
                return true; // 返回处理完成
            });
        $response->send();
         return $response;
    }

    public function clear_cookie(){

        // echo Cookie::get('Cookie_Access_Token');

        Cache::rm('Cache_Access_Token');
        Cache::rm('Cache_Ticket');

        return toJson(['message'=>'Cookie删除成功','code'=>200]);
    }

    //微信授权登录
    public function login(){
        // 获取code
        $code = trim($this->request->param('code'));
        $type = trim($this->request->param('type'));//wx
        if(empty($code)){
            return toJson(['message'=>'参数不全，请检查','code'=>400]);
        }
        
        if($type == 'wx'){
         $app = Factory::miniProgram(Config::get('wx_config'));
         $res = $app->auth->session($code);

         if($res['openid']){
            $userinfo = $this->find('user','openid = "'.$res['openid'].'" and deleteTime is null');
            if(empty($userinfo)){
                $data = [
                    'openid' => $res['openid'],
                    'nickname' => $this->request->param('nickName'),
                    'sex' => $this->request->param('gender'),
                    'city' => $this->request->param('city'),
                    'createtime' => time()
                ];
                $this->insert('user',$data);
                $userinfo = $this->find('user','openid = "'.$res['openid'].'" and deleteTime is null');
            }
            // Session::set('Session_User_'.$token, $userinfo['openid']);
            
            //获取jwt句柄
            $jwtAuth = $this->jwtAuth;
            $token = $jwtAuth->setUid($userinfo['openid'])->encode()->getToken(); //包裝uid 跟用戶權限
            $redata =[
                'token'=>$token,
                'userData'=>$userinfo,
                'headimgurl'=> $userinfo['headimgurl']?:'',
                'subscribe'=> $userinfo['subscribe'],
                'ismoblie'=> $userinfo['mobile']?:0,
                'isIdentitycard'=> $userinfo['identitycard']?:0,
                'isPersonVerify'=> $userinfo['is_person_verify']?:0
            ];
            return toJson($redata);
            }
        }
        /**end 小程序登录**/
    
        /**normal login**/
        //已登录处理
        $token = $this->request->header('token');
        if($token){
            $openid = Session::get('Session_User_'.$token);

            $userData = UserModel::where('username','eq',$openid)->where('deleteTime is null')->find();
            if($userData){
                $userinfo = $this->wechatOA->get_user_info($code);


                if(empty($userinfo)){
                    return toJson(['message'=>'微信授权失败','code'=>400]);
                }
                if($userinfo->subscribe == 1){
                    if($userinfo->headimgurl != $userData->headimgurl ){
                        $userData->headimgurl = $userinfo->headimgurl;
                        $userData->subscribe  = $userinfo->subscribe;
                        $userData->nickname = $userinfo->nickname;
                        $userData->sex = $userinfo->sex;
                        $userData->city = $userinfo->city;
                        $userData->save();
                }

                }


                $ismobile = empty($userData->mobile) ? 0 : 1;
                $isIdentitycard = empty($userData->identitycard) ? 0 : 1;  
                $isPersonVerify = empty($userData->is_person_verify) ? 0 : 1;     
                // $subscribe = isset($userinfo->unionid) ? 1 : 0; 
                return toJson(['token'=>$token,'userData'=>$userData,'headimgurl'=>$userinfo->headimgurl,'subscribe'=>$userinfo->subscribe,'ismoblie'=>$ismobile,'isIdentitycard'=>$isIdentitycard,'isPersonVerify'=>$isPersonVerify]);
            }
        }

    
        $userinfo = $this->wechatOA->get_user_info($code);
        
        if(empty($userinfo) || $userinfo==false){

            return toJson(['message'=>'微信授权失败','code'=>400]);
        }


        $userData = UserModel::where('openid','eq',$userinfo->openid)->where('deleteTime is null')->find();
        if(empty($userData)){
            $userData = new UserModel;
            $userData->openid = $userinfo->openid;
            $userData->createtime = time();
            $userData->headimgurl = @$userinfo->headimgurl?:'';
            $userData->save();
        }else{

            if($userinfo->subscribe !=$userData->subscribe ){
                $userData->subscribe = $userinfo->subscribe;
               
            }

            if($userinfo->subscribe == 1){
                if($userinfo->headimgurl != $userData->headimgurl ){
                    $userData->headimgurl = $userinfo->headimgurl;
                }
            if($userinfo->headimgurl != $userData->headimgurl){
                $userData->headimgurl = $userinfo->headimgurl;
               
            }
            $userData->nickname = $userinfo->nickname;
            $userData->sex = $userinfo->sex;
            $userData->city = $userinfo->city;
            }
            $userData->save();
        }

        //获取jwt句柄
        $jwtAuth = $this->jwtAuth;
        $token = $jwtAuth->setUid($userinfo->openid)->encode()->getToken(); //包裝uid 跟用戶權限
        // $token = makeToken();
        // Session::set('Session_User_'.$token, $userinfo->openid);
        $ismobile = empty($userData->mobile) ? 0 : 1;
        $isIdentitycard = empty($userData->identitycard) ? 0 : 1;  
        $isPersonVerify = empty($userData->is_person_verify) ? 0 : 1;   
        // $subscribe = isset($userinfo->unionid) ? 1 : 0; 
        $headimgurl = @$userinfo->subscribe==1?$userinfo->headimgurl:'';
        return toJson(['token'=>$token,'userData'=>$userData,'subscribe'=>$userinfo->subscribe,'headimgurl'=>$headimgurl,'ismoblie'=>$ismobile,'isIdentitycard'=>$isIdentitycard,'isPersonVerify'=>$isPersonVerify]);

    }



    /**
     * 获取JS-SDK调用权限
     */
    public function share(){
        $url = trim($this->request->param('url'));
        if(empty($url)){
            return toJson(['message'=>'参数不全，请检查','code'=>400]);
        }
        $share_config = $this->wechatOA->get_share_config($url);
        if(empty($share_config)){
            return toJson(['message'=>'微信授权失败','code'=>400]);            
        }
        return toJson($share_config);
    }


    public function valid(){  
        $echoStr = trim($this->request->param('echostr'));  
        //valid signature , option  
        if($this->checkSignature()){  
            header('content-type:text');  
            echo $echoStr;  
            exit;  
        }  
    }   


    private function checkSignature(){  
        $signature = trim($this->request->param('signature'));
        $timestamp = trim($this->request->param('timestamp'));
        $nonce = trim($this->request->param('nonce'));

        $token = $this->token;  
        $tmpArr = array($token, $timestamp, $nonce);  
        sort($tmpArr);  
        $tmpStr = implode( $tmpArr );  
        $tmpStr = sha1( $tmpStr );  

        if( $tmpStr == $signature ){  
            return true;  
        }else{  
            return false;  
        }  
    }
    

}